import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, {
  DrawerForm,
  ProFormCheckbox,
  ProFormDependency,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import { Card, Checkbox, Col, Divider, Row } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';

import * as apiAreaFilter from '@/services/areaFilter';
import * as c from '@/services/consts';
import { ProFormRadio } from '@ant-design/pro-components';
import { CheckboxValueType } from 'antd/es/checkbox/Group';

type FormProps = {
  visible: boolean;
  defaultProductId: number | undefined;
  current: API.Ad | undefined;
  onCancel: () => void;
  onSubmit: (values: API.Ad) => Promise<void>;
};

const Form: React.FC<FormProps> = (props) => {
  const { visible, defaultProductId, current, onCancel, onSubmit } = props;
  if (!visible) {
    return null;
  }

  let defaultCurrent: Partial<API.Ad> | undefined = undefined;
  if (!current) {
    defaultCurrent = {
      productId: defaultProductId,
      adPlatform: c.AdPlatform.Self.value,
      //position: c.AdType.Banner.value,
      // config: { timeout: 15, closeDelay: 3, autoPlay: true },
      sort: 1,
      status: true,
    };
  }

  //console.log('refData: ', current?.refData);

  let defaultRefData: API.AdRefItem[] =
    current && current.refData ? current.refData : [];

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultRefData.map((item) => item.id),
  );
  const [refDataSource, setRefDataSource] = useState<API.AdRefItem[]>(
    () => defaultRefData,
  );

  let defaultPlatformAppVerCompareData: API.AppVerComparePolicy[] =
    current && current.policy?.platformAppVerCompares
      ? current.policy?.platformAppVerCompares
      : [];

  const [
    editablePlatformAppVerCompareKeys,
    setEditablePlatformAppVerCompareKeys,
  ] = useState<React.Key[]>(() =>
    defaultPlatformAppVerCompareData.map((item) => item.id),
  );
  const [platformAppVerCompareDataSource, setPlatformAppVerCompareDataSource] =
    useState<API.AppVerComparePolicy[]>(() => defaultPlatformAppVerCompareData);
  const [checkedList, setCheckedList] = useState<any[]>(
    current?.policy?.displayAreaFilterPolicyAreaFilterIds,
  );
  const [policyAreaList, setPolicyAreaList] = useState<any[]>([]);
  const [currentProductId, setCurrentProductId] = useState<number>(
    current?.productId,
  );

  const formRef = useRef<ProFormInstance>();

  const { getProduct, getProductOptions } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      getProductOptions: model.getProductOptions,
    }),
  );

  const productOptions = getProductOptions(false);

  // const loadAreaFilters = async (params: { [key: string]: any }) => {
  //   const result = await apiAreaFilter.all(params);

  //   //console.log('loadAreaFilters: ', result);

  //   if (result.success && result.data && result.data.length > 0) {
  //     let options: any[] = [];
  //     for (let item of result.data) {
  //       let product = getProduct(item.productId);
  //       let areas =
  //         item.areaGroup == c.AreaGroup.Foreign.value
  //           ? item.areas
  //           : item.areaGroup;

  //       options.push({
  //         label: `(${product?.name})${item.name} [${areas}]`,
  //         value: item.id,
  //         disabled: !item.status,
  //       });
  //     }

  //     return Promise.resolve(options);
  //   }

  //   return Promise.resolve([]);
  // };

  const loadAreaFilters = async (params: { [key: string]: any }) => {
    const result = await apiAreaFilter.all(params);

    console.log('loadAreaFilters: ', params, result);

    if (result.success && result.data && result.data.length > 0) {
      let options: any[] = [];
      for (let item of result.data) {
        let product = getProduct(item.productId);
        let areas =
          item.areaGroup == c.AreaGroup.Foreign.value
            ? item.areas
            : item.areaGroup;

        options.push({
          label: `(${product?.name})${item.name} [${areas}]`,
          value: item.id,
          disabled: !item.status,
        });
      }
      // console.log(options);

      setPolicyAreaList(options);
      //return Promise.resolve(options);
    } else {
      setPolicyAreaList([]);
    }
    // return Promise.resolve([]);
  };

  useEffect(() => {
    loadAreaFilters({ productIds: [currentProductId] });
  }, [currentProductId]);

  const handleFormSubmit = async (record: API.Ad) => {
    //console.log(refDataSource);
    record.refData = refDataSource;

    if (!record.policy) {
      record.policy = {} as API.AdPolicy;
    }
    record.policy.displayAreaFilterPolicyAreaFilterIds = checkedList;
    record.policy.platformAppVerCompares = platformAppVerCompareDataSource;

    onSubmit(record);
  };

  const onCheckChange = (list: CheckboxValueType[]) => {
    console.log(list);
    setCheckedList(list);
  };

  const refDataColumns: ProColumns<API.AdRefItem>[] = [
    {
      title: '广告ID',
      dataIndex: 'adId',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '请输入广告ID' }],
        };
      },
    },
    {
      title: '图片URL',
      dataIndex: 'imageUrl',
    },
    {
      title: '链接URL(wvs://或wv://以WebView展示)',
      dataIndex: 'linkUrl',
    },
    // {
    //   title: '仅黑名单用户可见',
    //   dataIndex: 'blacklistUserDisplay',
    //   valueType: 'switch',
    //   width: 80,
    // },
    {
      title: '启用',
      dataIndex: 'enabled',
      valueType: 'switch',
      width: 80,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 60,
    },
  ];

  const platformAppVerCompareColumns: ProColumns<API.AppVerComparePolicy>[] = [
    {
      title: '平台',
      dataIndex: 'platform',
      width: 120,
      valueType: 'select',
      fieldProps: {
        options: c.PlatformOptions,
      },
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '请选择平台' }],
        };
      },
    },
    {
      title: '比较方式',
      dataIndex: 'compareMode',
      width: 120,
      valueType: 'select',
      fieldProps: {
        options: c.AdPolicyAppVerCompareOptions,
      },
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '请选择比较方式' }],
        };
      },
    },
    {
      title: '版本号',
      width: 80,
      dataIndex: 'appVer',
      valueType: 'digit',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '请填写版本号比较方式' }],
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 60,
    },
  ];

  const renderAdMobFormItems = (adType: string) => {
    const adSlotOptions = c.AdMobTypeSlots[adType] ?? [''];
    return (
      <>
        <Row gutter={24}>
          <Col span={12}>
            <ProFormSelect
              name="adSlot"
              label="广告位"
              options={adSlotOptions}
              rules={[{ required: true }]}
            />
          </Col>
        </Row>
      </>
    );
  };

  const renderAdMobNaviteFormItems = (adType: string) => {
    const adSlotOptions = c.AdMobTypeSlots[adType] ?? [''];
    return (
      <>
        <Row gutter={24}>
          <Col span={12}>
            <ProFormSelect
              name="adSlot"
              label="广告位"
              options={adSlotOptions}
              rules={[{ required: true }]}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name={['config', 'size']}
              label="尺寸"
              options={c.AdMobNaviteSizeOptions}
              rules={[{ required: true }]}
            />
          </Col>
        </Row>
      </>
    );
  };

  const renderTopOnInterstitialFormItems = () => {
    const adSlotOptions = c.AdTopOnSlots[c.AdType.Interstitial.value] ?? [''];
    return (
      <>
        <Row gutter={24}>
          <Col span={12}>
            <ProFormSelect
              name={['config', 'position']}
              label="广告位"
              options={adSlotOptions}
              rules={[{ required: true }]}
            />
          </Col>
          <Col span={12}>
            <ProFormText name={['config', 'sceneId']} label="场景ID" />
          </Col>
          <Col span={12}>
            <ProFormSwitch
              name={['config', 'vpnConnected']}
              label="Trigger"
              checkedChildren="连接后触发"
              unCheckedChildren="连接前触发"
            />
          </Col>
        </Row>
      </>
    );
  };

  const renderTopOnBannerFormItems = () => {
    const adSlotOptions = c.AdTopOnSlots[c.AdType.Banner.value] ?? [''];
    return (
      <>
        <Row gutter={24}>
          <Col span={12}>
            <ProFormSelect
              name={['config', 'position']}
              label="广告位"
              options={adSlotOptions}
              rules={[{ required: true }]}
            />
          </Col>
          <Col span={12}>
            <ProFormText name={['config', 'sceneId']} label="场景ID" />
          </Col>
          <Col span={12}>
            <ProFormDigit
              name={['config', 'width']}
              label="Width"
              placeholder={'320'}
              min={0}
              rules={[{ required: true }]}
            />
          </Col>
          <Col span={12}>
            <ProFormDigit
              name={['config', 'height']}
              label="Height"
              placeholder={'50'}
              min={0}
              rules={[{ required: true }]}
            />
          </Col>
        </Row>
      </>
    );
  };

  const renderAdSelfFormItems = (adType: string) => {
    return null;
  };

  const renderAdSelfFloatingFormItems = (adType: string) => {
    // return (
    //   <>
    //     <Row gutter={24}>
    //       <Col span={12}>
    //         <ProFormSwitch name={['config', 'closeable']} label="允许关闭" />
    //       </Col>
    //     </Row>
    //   </>
    // );
    return null;
  };

  return (
    <DrawerForm<API.Ad>
      open={visible}
      formRef={formRef}
      autoFocusFirstInput
      width={1224}
      title={`${current ? '编辑' : '添加'}广告`}
      initialValues={current ? current : defaultCurrent}
      onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
    >
      <Row gutter={24}>
        <Col span={24}>
          <ProFormSelect
            name="productId"
            label="产品"
            options={productOptions}
            rules={[{ required: true, message: '请选择产品' }]}
            // fieldProps={{
            //   onChange(value, option) {
            //     // console.log(value, option);
            //     loadAreaFilters({productIds: [value]})
            //   },
            // }}
          />
        </Col>
      </Row>
      <Row gutter={24}>
        <Col span={12}>
          <ProFormSelect
            name="adPlatform"
            label="广告平台"
            options={c.AdPlatformOptions}
            rules={[{ required: true }]}
          />
        </Col>
        <Col span={12}>
          <ProFormDependency name={['adPlatform']}>
            {({ adPlatform }) => {
              const adTypeOptions = c.AdPlatformTypes[adPlatform] ?? [''];

              return (
                <>
                  {/* <ProFormCheckbox.Group
                    name="adTypes"
                    label="广告类型"
                    options={adTypeOptions}
                    rules={[{ required: true, message: '请选择广告类型' }]}
                  /> */}
                  <ProFormRadio.Group
                    name="adType"
                    label="广告类型"
                    options={adTypeOptions}
                    rules={[{ required: true, message: '请选择广告类型' }]}
                  />
                </>
              );
            }}
          </ProFormDependency>
        </Col>
      </Row>
      <ProFormDependency name={['adPlatform', 'adTypes']}>
        {({ adPlatform, adTypes }) => {
          if (adPlatform == c.AdPlatform.AdMob.value) {
            if (adTypes != null && adTypes.includes(c.AdType.AppOpen.value)) {
              return renderAdMobFormItems(c.AdType.AppOpen.value);
            } else if (
              adTypes != null &&
              adTypes.includes(c.AdType.Interstitial.value)
            ) {
              return renderAdMobFormItems(c.AdType.Interstitial.value);
            } else if (
              adTypes != null &&
              adTypes.includes(c.AdType.Banner.value)
            ) {
              return renderAdMobFormItems(c.AdType.Banner.value);
            } else if (
              adTypes != null &&
              adTypes.includes(c.AdType.Native.value)
            ) {
              return renderAdMobNaviteFormItems(c.AdType.Native.value);
            }
          } else if (adPlatform == c.AdPlatform.TopOn.value) {
            if (
              adTypes != null &&
              adTypes.includes(c.AdType.Interstitial.value)
            ) {
              return renderTopOnInterstitialFormItems();
            } else if (
              adTypes != null &&
              adTypes.includes(c.AdType.Banner.value)
            ) {
              return renderTopOnBannerFormItems();
            } else {
              return (
                <>
                  <Row gutter={24}>
                    <Col span={12}>
                      <ProFormText
                        name={['config', 'sceneId']}
                        label="场景ID"
                      />
                    </Col>
                  </Row>
                </>
              );
            }
          } else if (adPlatform == c.AdPlatform.Self.value) {
            if (adTypes != null && adTypes.includes(c.AdType.Floating.value)) {
              return renderAdSelfFloatingFormItems(c.AdType.Floating.value);
            }
          }
          return null;
        }}
      </ProFormDependency>
      <Row gutter={24}>
        <Col span={24}>
          <ProForm.Item name="refData" label="广告资源">
            <EditableProTable<API.AdRefItem>
              rowKey="id"
              locale={{ emptyText: '暂无数据' }}
              toolBarRender={false}
              columns={refDataColumns}
              defaultValue={refDataSource}
              // onChange={setRefDataSource}
              onChange={(value: API.AdRefItem[]) => {
                setRefDataSource(value);
              }}
              recordCreatorProps={{
                // newRecordType: 'cache',
                newRecordType: 'dataSource',
                position: 'bottom',
                record: () => ({
                  id: `${Date.now()}`,
                  enabled: true,
                }),
              }}
              editable={{
                type: 'multiple',
                //type: 'single',
                editableKeys,
                actionRender: (row, config, defaultDom) => [
                  //defaultDom.save,
                  defaultDom.delete,
                ],
                onValuesChange: (record, recordList) => {
                  setRefDataSource(recordList);
                },
                onChange: setEditableRowKeys,
              }}
              request={async () => ({
                data: refDataSource,
                success: true,
              })}
              params={{ d: refDataSource }}
            />
          </ProForm.Item>
        </Col>
      </Row>
      <Row gutter={24}>
        <Col span={12}>
          <ProFormDigit
            name="sort"
            label="排序"
            wrapperCol={{ span: 4 }}
            min={0}
            max={9999}
            fieldProps={{ defaultValue: 0 }}
            rules={[{ required: true }]}
          />
        </Col>
        <Col span={12}>
          <ProFormSwitch name="status" label="状态" />
        </Col>
      </Row>

      <Row gutter={24}>
        <Col span={24}>
          <ProFormTextArea name="remark" label="备注" />
        </Col>
      </Row>
      <Card title="显示策略" style={{ margin: 0, padding: 0 }}>
        <Row gutter={24}>
          <Col span={12}>
            <ProFormCheckbox.Group
              name="memberLevels"
              label="用户等级"
              options={c.MemberLevelOptions}
              rules={[{ required: true, message: '请选择用户等级' }]}
            />
          </Col>
          <Col span={12}>
            <ProFormSwitch
              name={['policy', 'blacklistUserDisplay']}
              label="仅黑名单用户可见"
            />
          </Col>
          <Col span={12}>
            <ProFormCheckbox.Group
              name="platforms"
              label="平台"
              options={c.PlatformOptions}
              rules={[{ required: true, message: '请选择平台' }]}
            />
          </Col>
          <Col span={12}>
            <ProFormCheckbox.Group
              name="channels"
              label="渠道"
              options={c.Channels}
              rules={[{ required: true, message: '请选择渠道' }]}
            />
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Divider orientation="left" orientationMargin="0">
              版本策略
            </Divider>
          </Col>
          {/* <Col span={12}>
            <ProFormSelect
              name={['policy', 'appVerCompare']}
              label="版本比较"
              options={c.AdPolicyAppVerCompareOptions}
            />
          </Col>
          <Col span={12}>
            <ProFormDigit name={['policy', 'appVer']} label="版本号" min={0} />
          </Col> */}
          <Col span={24}>
            <ProForm.Item name={['policy', 'platformAppVerCompares']} label="">
              <EditableProTable<API.AppVerComparePolicy>
                rowKey="id"
                locale={{ emptyText: '暂无数据' }}
                toolBarRender={false}
                columns={platformAppVerCompareColumns}
                defaultValue={platformAppVerCompareDataSource}
                onChange={(value: API.AppVerComparePolicy[]) => {
                  setPlatformAppVerCompareDataSource(value);
                }}
                recordCreatorProps={{
                  newRecordType: 'dataSource',
                  position: 'bottom',
                  record: () => ({
                    id: `${Date.now()}`,
                    appVer: 0,
                  }),
                }}
                editable={{
                  type: 'multiple',
                  editableKeys: editablePlatformAppVerCompareKeys,
                  actionRender: (row, config, defaultDom) => [
                    //defaultDom.save,
                    defaultDom.delete,
                  ],
                  onValuesChange: (record, recordList) => {
                    setPlatformAppVerCompareDataSource(recordList);
                  },
                  onChange: setEditablePlatformAppVerCompareKeys,
                }}
                request={async () => ({
                  data: platformAppVerCompareDataSource,
                  success: true,
                })}
                // params={{ d: platformAppVerCompareDataSource }}
              />
            </ProForm.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Divider orientation="left" orientationMargin="0">
              地区策略
            </Divider>
          </Col>
          <Col span={12}>
            <ProFormSelect
              name={['policy', 'displayAreaFilterPolicy']}
              label="策略"
              options={c.GroupDisplayAreaFilterPolicyOptions}
            />
          </Col>
          <Col span={12}>
            <ProFormDependency name={['productId']}>
              {({ productId }) => {
                setCurrentProductId(productId);
                return (
                  // <ProFormCheckbox.Group
                  //   name={['policy', 'displayAreaFilterPolicyAreaFilterIds']}
                  //   label="地区"
                  //   params={{ productIds: [productId] }}
                  //   request={loadAreaFilters}
                  // />
                  <Checkbox.Group
                    key="cgAreas"
                    value={checkedList}
                    onChange={onCheckChange}
                    style={{ marginBottom: 30 }}
                  >
                    <Row>
                      <Col span={24}>地区</Col>
                      {policyAreaList.map((val) => {
                        return (
                          <Col span={12}>
                            <Checkbox
                              key="cbAreas"
                              value={val.value}
                              disabled={val.disabled}
                            >
                              {val.label}
                            </Checkbox>
                          </Col>
                        );
                      })}
                    </Row>
                  </Checkbox.Group>
                );
              }}
            </ProFormDependency>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Divider orientation="left" orientationMargin="0">
              研发测试设置
            </Divider>
          </Col>
          <Col span={12}>
            <ProFormTextArea
              name="forceDisplayUsers"
              label="强制显示用户(多用户换行)"
              fieldProps={{ rows: 8 }}
            />
          </Col>
          <Col span={12}>
            <ProFormTextArea
              name="ipMoveUsers"
              label="IP漂移用户(多用户换行)"
              fieldProps={{ rows: 8 }}
            />
          </Col>
        </Row>
      </Card>
    </DrawerForm>
  );
};

export default Form;
